﻿using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using Heimdallr.Net;

/*
 * This is a server application which is using HTTP multipart stream and long-polling mechanism to publish text message to clients.
 */

namespace Heimdallr.Sample.ChatRoom.Server
{
    class Program
    {
        static readonly HttpElement httpElement = new HttpElement(GetLocalIPAddress().ToString());

        static void Main(string[] args)
        {
            ServiceElementController<HttpElement> controller = new ServiceElementController<HttpElement>(httpElement);

            httpElement.Modules.Add(new CustomMultipartResponseModule());
            httpElement.Modules.Add(new CustomPollingResponseModule());
            httpElement.Modules.Add(new CustomRequestModule());
            httpElement.Notify += HttpElement_Notify;
            httpElement.Error += HttpElement_Error;
            httpElement.StatusChanged += HttpElement_StatusChanged;

            controller.Start();

            do
                Console.WriteLine("Enter 'exit' to leave...");
            while (Console.ReadLine().ToLowerInvariant() != "exit");

            controller.Stop();
        }

        static void HttpElement_Notify(object sender, FireNotificationEventArgs e)
        {
            httpElement.Publish(e.Notification);
        }

        static void HttpElement_StatusChanged(object sender, StatusChangedEventArgs e)
        {
            Console.WriteLine("Chat Room Server Status: {0} -> {1}", e.OldStatus, e.NewStatus);
        }

        static void HttpElement_Error(object sender, ExceptionsEventArgs e)
        {
            Console.WriteLine("Chat Room Server Error(s): ");
            Console.WriteLine(e);
        }

        static IPAddress GetLocalIPAddress()
        {
            IPAddress result = Dns.GetHostAddresses(Dns.GetHostName()).FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);

            if (result == null)
                return IPAddress.Loopback;
            else
                return result;
        }
    }
}
